package cn.itsource.org.service.impl;

import cn.itsource.basic.service.BaseServiceImpl;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.TreeUtil;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

@Service //交给spring管理
public class DepartmentServiceImpl extends BaseServiceImpl<Department,DepartmentQuery> implements IDepartmentService {

    /**
     * 注入mapper
     */
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void saveOrUpdate(Department department) {
        //保留老的dirPath
        String oldDirPath = department.getDirPath();

        //验证入参 "" null "    "
        /*if (StringUtils.isBlank(department.getName())){
            throw new RuntimeException("请输入部门名称");
        }
        if (StringUtils.isBlank(department.getSn())){
            throw new RuntimeException("请输入部门编号");
        }*/

        if (department.getId() == null) {

            //只有设置了值的字段才会被插入
            departmentMapper.insertSelective(department);

            //调用方法
            updateDept(department);

        }else{

            //调用方法
            //parentIds : [3,8,9]
            String newDirPath =  updateDept(department);

            //1.根据id查询对象 dirPath之前的/3/8
            Department dbDept = departmentMapper.selectByPrimaryKey(department.getId());

            //2.根据oldDirPath : /3/8去like数据
            List<Department> list = departmentMapper.likeByDirPath(oldDirPath);

            //3.like到的数据 /3/8/9 替换成 /1/8/9
            for (Department needUpdateDept : list) {
                //4替换字符串                           /3/8/9                 /3/8          /1/8
                needUpdateDept.setDirPath(needUpdateDept.getDirPath().replace(oldDirPath,newDirPath));
                //5.修改入库就行了
                departmentMapper.updateByPrimaryKeySelective(needUpdateDept);
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("/3/8/9".replace("/3/8", "/1/8"));
    }

    private String updateDept(Department department) {
        //parentIds : [3,8,9]
        Long[] parentIds = department.getParentIds();

        //判断不能选择自己为自己的上级 [3,8,9,8]

        ArrayList<Long> list = new ArrayList<>(Arrays.asList(parentIds));
        list.add(department.getId());
        //去重
        HashSet<Long> set = new HashSet<>(list);
        //如果变少了，代表有重复的，选择了重复的上级
        if (list.size() != set.size()){
            throw new RuntimeException("不能选择自己为上级");
        }

        StringBuilder sb = new StringBuilder();
        if (parentIds != null && parentIds.length > 0) {

            //1.获取这里面的9
            Long parentId = parentIds[parentIds.length - 1];
            department.setParentId(parentId);
            //2.拼接dirPath字段 假设自增id20  /3/8/9/20
            //循环  id ：实例 parentIds：数据源
            for (Long id : parentIds) {
                sb.append("/").append(id);
            }
            //拼接字符串
            sb.append("/").append(department.getId());

        } else {
            department.setParentId(null);
            //拼接字符串
            sb.append("/").append(department.getId());
        }
        //设置字段的值
        department.setDirPath(sb.toString());
        //3.进行修改
        departmentMapper.updateByPrimaryKey(department);

        return sb.toString();
    }

    /**
     * 分页方法
     * @param query 高级查询对象
     * @return 分页数据 （total  list）
     */
    @Override
    public PageList<Department> findPage(DepartmentQuery query) {
        //1.使用分页插件
        PageHelper.startPage(query.getPage(),query.getSize());

        //2.执行查询方法
        List<Department> departments = departmentMapper.findPage(query);

        //3.封装pageInfo
        PageInfo<Department> pageInfo = new PageInfo<>(departments);

        //4.封装并返回分页对象
        return new PageList<>(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public List<Department> findParentDepts() {
        return departmentMapper.findParentDepts();
    }

    @Override
    public List<Department> treeDept() {

        //1.查询所有的部门
        List<Department> list = departmentMapper.selectAll();

        //2.调用工具类的方法，搞定
        List<Department> tree = TreeUtil.getTree(list);

        return tree;
    }

}
